/**
 * 
 */
package com.yi.model.internal.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.yi.model.objects.DBDefinitions;
import com.yi.model.objects.Model;

/**
 * @author yilo
 *
 */
public class ModelApi {
	public Model convertEntityToModel(DBObject entity){
		Model model = new Model();
		if(entity.get(DBDefinitions.col_id) != null) model.id = entity.get(DBDefinitions.col_id).toString();
		if(entity.get(DBDefinitions.col_name) != null) model.name = entity.get(DBDefinitions.col_name).toString();
		if(entity.get(DBDefinitions.col_desc) != null) model.desc = entity.get(DBDefinitions.col_desc).toString();
		if(entity.get(DBDefinitions.col_created) != null) model.created = entity.get(DBDefinitions.col_created).toString();
		if(entity.get(DBDefinitions.col_updated) != null) model.updated = entity.get(DBDefinitions.col_updated).toString();
		if(entity.get(DBDefinitions.col_fields) != null) model.fields = ((Map<String,Object>)entity.get(DBDefinitions.col_fields));

		return model;
	}
	
	public DBObject convertModelToEntity(Model model){
		DBObject entity = new BasicDBObject();
		if(StringUtils.hasLength(model.id))  entity.put(DBDefinitions.col_id, model.id);
		if(StringUtils.hasLength(model.name))  entity.put(DBDefinitions.col_name, model.name);
		if(StringUtils.hasLength(model.desc))  entity.put(DBDefinitions.col_desc, model.desc);
		try {
			if(StringUtils.hasLength(model.created))
				entity.put(DBDefinitions.col_created, new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm:ss").parse(model.created));
			else
				entity.put(DBDefinitions.col_created, new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm:ss").format(new Date()));
			
			if(StringUtils.hasLength(model.updated))
				entity.put(DBDefinitions.col_updated, new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm:ss").parse(model.updated));
			else
				entity.put(DBDefinitions.col_updated, new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm:ss").format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(model.fields != null && model.fields.size() > 0){			
			entity.put(DBDefinitions.col_fields, model.fields);			
		}
		return entity;
	}
}
